package com.example.gate.net;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: Allen
 * @create: 2025/7/9 10:53
 * @description:
 **/
@Slf4j
@Component
public class SessionGroup {

    /**
     * 账号临时session
     */
    private final ConcurrentHashMap<Long,AccountSession> tempAccountSessions = new ConcurrentHashMap<>();
    /**
     * 用户登录成功后的session
     */
    private final ConcurrentHashMap<Integer,ClientUserSession> userSessions = new ConcurrentHashMap<>();


    public ClientUserSession getUserSession(int userId) {
        return userSessions.get(userId);
    }

    public AccountSession getAccountSession(long accountId) {
        return tempAccountSessions.get(accountId);
    }

    public void addAccountSession(AccountSession accountSession) {
        tempAccountSessions.put(accountSession.getAccountId(), accountSession);
    }


    public void addUserSession(ClientUserSession userSession) {
        userSessions.put(userSession.getUserId(), userSession);
    }

    public void removeUserSession(int userId) {
        ClientUserSession remove = userSessions.remove(userId);
        if (remove != null)
            tempAccountSessions.remove(remove.getAccountId());
    }

    public void removeAccountSession(long accountId) {
        tempAccountSessions.remove(accountId);
    }

    public void tempAccountLogin(Channel channel, long accountId) {
        AccountSession accountSession = new AccountSession(channel,accountId,0);
        tempAccountSessions.computeIfAbsent(accountId, k -> accountSession);
    }

    public void tempUserLogin(Channel channel, long accountId, int userId) {
        ClientUserSession userSession = new ClientUserSession(channel,accountId,userId);
        userSessions.put(userId, userSession);
        tempAccountSessions.remove(accountId);
    }

}
